# 海龟编辑器适配版（Pygame简化）
import turtle
import time
import random
import os

# 初始化画布
wn = turtle.Screen()
wn.title("贪吃蛇游戏")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)  # 关闭自动刷新

# 分数系统
score = 0
high_score = 0

# 尝试加载历史分数
if os.path.exists("score.txt"):
    with open("score.txt", "r") as f:
        high_score = int(f.read())

# 蛇头
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("green")
head.penup()
head.goto(0, 0)
head.direction = "stop"

# 食物
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0, 100)

# 道具（加速/减速）
powerup = turtle.Turtle()
powerup.speed(0)
powerup.shape("square")
powerup.penup()
powerup.hideturtle()
powerup_type = ""  # speed_up 或 speed_down

# 蛇身列表
segments = []

# 显示分数的画笔
pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write(f"得分: {score}  历史最高分: {high_score}", align="center", font=("Arial", 24, "normal"))

# 方向控制函数
def go_up():
    if head.direction != "down":
        head.direction = "up"

def go_down():
    if head.direction != "up":
        head.direction = "down"

def go_left():
    if head.direction != "right":
        head.direction = "left"

def go_right():
    if head.direction != "left":
        head.direction = "right"

# 移动函数
def move():
    if head.direction == "up":
        y = head.ycor()
        head.sety(y + 20)

    if head.direction == "down":
        y = head.ycor()
        head.sety(y - 20)

    if head.direction == "left":
        x = head.xcor()
        head.setx(x - 20)

    if head.direction == "right":
        x = head.xcor()
        head.setx(x + 20)

# 键盘绑定
wn.listen()
wn.onkeypress(go_up, "w")
wn.onkeypress(go_down, "s")
wn.onkeypress(go_left, "a")
wn.onkeypress(go_right, "d")
wn.onkeypress(go_up, "Up")
wn.onkeypress(go_down, "Down")
wn.onkeypress(go_left, "Left")
wn.onkeypress(go_right, "Right")

# 生成道具
def generate_powerup():
    global powerup_type
    powerup.hideturtle()
    x = random.randint(-380, 380)
    y = random.randint(-280, 280)
    powerup_type = random.choice(["speed_up", "speed_down"])
    if powerup_type == "speed_up":
        powerup.color("blue")
    else:
        powerup.color("yellow")
    powerup.goto(x, y)
    powerup.showturtle()

# 主循环
speed = 0.1
powerup_active = False
game_running = True

while game_running:
    wn.update()  # 手动刷新画面

    # 检查是否撞到边界
    if head.xcor() > 390 or head.xcor() < -390 or head.ycor() > 290 or head.ycor() < -290:
        time.sleep(1)
        head.goto(0, 0)
        head.direction = "stop"
        
        # 隐藏所有蛇身
        for segment in segments:
            segment.goto(1000, 1000)
        segments.clear()
        
        # 保存分数
        if score > high_score:
            high_score = score
            with open("score.txt", "w") as f:
                f.write(str(high_score))
        score = 0
        powerup_active = False
        powerup.hideturtle()
        
        # 更新分数显示
        pen.clear()
        pen.write(f"得分: {score}  历史最高分: {high_score}", align="center", font=("Arial", 24, "normal"))

    # 检查是否吃到食物
    if head.distance(food) < 20:
        # 移动食物到随机位置
        x = random.randint(-380, 380)
        y = random.randint(-280, 280)
        food.goto(x, y)
        
        # 加分
        score += 10
        pen.clear()
        pen.write(f"得分: {score}  历史最高分: {high_score}", align="center", font=("Arial", 24, "normal"))
        
        # 30%概率生成道具
        if random.random() < 0.3:
            generate_powerup()
            powerup_active = True
        else:
            powerup_active = False
            powerup.hideturtle()
        
        # 添加蛇身
        new_segment = turtle.Turtle()
        new_segment.speed(0)
        new_segment.shape("square")
        new_segment.color("grey")
        new_segment.penup()
        segments.append(new_segment)

    # 检查是否吃到道具
    if powerup_active and head.distance(powerup) < 20:
        powerup.hideturtle()
        powerup_active = False
        
        # 应用道具效果
        if powerup_type == "speed_up":
            speed *= 0.7  # 加速（值越小越快）
        else:
            speed *= 1.3  # 减速
        powerup_type = ""

    # 移动蛇身
    for index in range(len(segments)-1, 0, -1):
        x = segments[index-1].xcor()
        y = segments[index-1].ycor()
        segments[index].goto(x, y)

    if len(segments) > 0:
        x = head.xcor()
        y = head.ycor()
        segments[0].goto(x, y)

    move()

    # 检查蛇头是否碰到蛇身
    for segment in segments:
        if segment.distance(head) < 20:
            time.sleep(1)
            head.goto(0, 0)
            head.direction = "stop"
            
            # 隐藏所有蛇身
            for segment in segments:
                segment.goto(1000, 1000)
            segments.clear()
            
            # 保存分数
            if score > high_score:
                high_score = score
                with open("score.txt", "w") as f:
                    f.write(str(high_score))
            score = 0
            powerup_active = False
            powerup.hideturtle()
            
            # 更新分数显示
            pen.clear()
            pen.write(f"得分: {score}  历史最高分: {high_score}", align="center", font=("Arial", 24, "normal"))

    time.sleep(speed)  # 控制速度

wn.mainloop()